<template>
  <div class="container">
    <el-table :data="products" border style="width: 100%">
      <el-table-column 
        v-for="column in columns" 
        :key="column.prop" 
        :prop="column.prop" 
        :label="column.label"
        :width="column.width">
        <template #default="{ row }" v-if="column.template">
          <template v-if="column.label === '数量'">
            <el-button type="danger" @click="decreaseQuantity(row)">-</el-button>
            <span style="margin: 0 10px">{{ row.quantity }}</span>
            <el-button type="primary" @click="increaseQuantity(row)">+</el-button>
          </template>
          <template v-else-if="column.label === '总价'">
            {{ computedTotal(row) }}
          </template>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="total-row">
      <span>总计：{{ calculateTotal }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElTable, ElTableColumn, ElButton } from 'element-plus'
import 'element-plus/dist/index.css'
import { useComputed } from './js/useComputed'

// 表格列定义
const columns = [
  { prop: 'name', label: '名称', width: '180' },
  { prop: 'price', label: '价格', width: '180' },
  { prop: 'quantity', label: '数量', width: '180', template: true },
  { prop: 'total', label: '总价', width: '180', template: true }
]

// 商品数据
const products = ref([
  { id: 1, name: 'iphone', price: 6000, quantity: 2 },
  { id: 2, name: 'ipad', price: 5000, quantity: 3 },
  { id: 3, name: 'mac', price: 10000, quantity: 5 }
])

// 计算单个商品总价
const calculateItemTotal = (item) => {
  //模拟耗时
// 模拟同步耗时操作
  let startTime = Date.now();
  while(Date.now() - startTime < 100) {} // 阻塞1秒
  console.log('calculateItemTotal', item.id) // 添加商品ID便于观察
  return item.price * item.quantity
}

// 使用缓存计算函数，确保只有当商品数量变化时才重新计算
const computedTotal = useComputed((item) => calculateItemTotal(item))
// 不使用缓存计算函数
// const computedTotal = (item) => calculateItemTotal(item)

// 计算所有商品总价，使用缓存的计算结果
const calculateTotal = computed(() => 
  products.value.reduce((total, item) => total + computedTotal(item).value, 0)
)

// 增加数量
const increaseQuantity = (item) => {
  item.quantity++
}

// 减少数量
const decreaseQuantity = (item) => {
  if (item.quantity > 0) item.quantity--
}
</script>

<style>
.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.total-row {
  margin-top: 20px;
  text-align: right;
  font-size: 16px;
  font-weight: bold;
}

.el-button {
  padding: 5px 12px;
}
</style>